package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class WebFiter implements Filter {
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
        //判断请求开放
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        String path = request.getServletPath();
        System.out.println("当前请求: "+path);
        if (path.contains("/images") || "/index.jsp".equals(path) || "/UserServlet".equals(path)||path.contains("/images/1.jpg")||path.contains("/static")){
            //允许访问 q
            arg2.doFilter(arg0,arg1);
        }else{
            Object username = request.getSession().getAttribute("username");
            if (username!=null){
                arg2.doFilter(arg0,arg1);
            }
            else{
                request.setAttribute("errorMsg","请先登录再访问");
                request.getRequestDispatcher("index.jsp").forward(request,response);
            }
        }
    }
    @Override
    public void destroy() {
    }
}
